import React, { useEffect, useState } from 'react';
import { Col, Input, Row, Table } from 'antd';
import styles from './style.modules.less';
import { useDebounceFn, useSet } from 'ahooks';
import { CloseOutlined } from '@ant-design/icons';
import { ColumnType } from 'antd/es/table';

export interface MultiListProps<T> {
  loading: boolean;
  value?: number[];
  options: T[];
  onChange?: (values: number[]) => void;
  onSearch?: (search: string) => void;
  columns?: string[];
  mode?: number;
  visible?: boolean;
}

export interface MultiListRow {
  id: number;
  name: string;
  remark: string;
}

function MultiList<T extends MultiListRow>(props: MultiListProps<T>) {
  const [search, setSearch] = useState('');
  const [data, { add, has, remove, reset }] = useSet<number>([]);
  const { run: setDebSearch } = useDebounceFn(
    v => {
      if (props.onSearch) {
        setSearch(v);
        props.onSearch(v);
      }
    },
    { wait: 300 },
  );

  const columns: ColumnType<T>[] = [
    {
      title: props.columns ? props.columns[0] : '显示名',
      dataIndex: 'name',
    },
    {
      title: props.columns ? props.columns[0] : '备注',
      dataIndex: 'remark',
    },
  ];

  useEffect(() => {
    if (props.value !== Array.from(data)) {
      reset();
      props.value?.forEach(v => add(v));
    }
  }, [props.value]);

  useEffect(() => {
    if (!props.visible) {
      if (props.onChange) {
        props.onChange([]);
      }
      reset();
    }
  }, [props.visible]);

  // 监听data.size的变动推送到form
  useEffect(() => {
    if (props.onChange) {
      props.onChange(Array.from(data));
    }
  }, [data.size]);

  // 行配置
  const onRow = (record: T) => {
    return {
      onClick: () => {
        if (has(record.id)) {
          remove(record.id);
        } else {
          add(record.id);
        }
      },
    };
  };
  return (
    <>
      <div className={styles.multi}>
        <Row>
          <Col span={14}>
            <div style={{ marginBottom: 15 }}>
              <Input
                placeholder={'请输入'}
                allowClear={true}
                onChange={v => {
                  setDebSearch(v.currentTarget.value);
                }}
              />
            </div>

            <Table
              rowKey={'id'}
              loading={props.loading}
              dataSource={
                props.options?.filter(v => {
                  if (!search) {
                    return true;
                  }
                  return (
                    v.name.search(search) > -1 || v.remark.search(search) > -1
                  );
                }) ?? []
              }
              scroll={{ y: 360 }}
              size={'small'}
              columns={columns}
              pagination={false}
              rowClassName={record => {
                return has(record.id) ? styles.tableActive : '';
              }}
              onRow={onRow}
            />
          </Col>

          <Col span={10}>
            <div className={styles.panel}>
              <div className={styles.title}>
                <label>已选择 ({data.size ?? 0})</label>

                <a onClick={() => reset()}>清空</a>
              </div>
              <div
                className={[
                  styles.content,
                  props.mode ? styles.modeBlock : '',
                ].join(' ')}
              >
                {Array.from(data).map(id => {
                  const item = props.options?.find(
                    item => item.id === id,
                  ) as any;
                  if (!item) {
                    return <>null</>;
                  }
                  return (
                    <div key={id} className={styles.contentItem}>
                      {item.name}

                      <span
                        className={styles.contentIcon}
                        onClick={() => remove(id)}
                      >
                        <CloseOutlined />
                      </span>
                    </div>
                  );
                })}
              </div>
            </div>
          </Col>
        </Row>
      </div>
    </>
  );
}

export default MultiList;
